import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author: 成金乘
 * @date: 2022/11/19 19:37
 * @description:
 */
public class JDBCSelectDemo {
    public static void main(String[] args) throws SQLException {
        //创建数据源
        DataSource datasource = new MysqlDataSource();
        //描述数据库位置
        ((MysqlDataSource)datasource).setURL("jdbc:mysql://127.0.0.1:3306/java106?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)datasource).setUser("root");
        ((MysqlDataSource)datasource).setPassword("111111");
        //连接服务器
        Connection connection = datasource.getConnection();
        //连接后构建sql语句
        String sql = "select * from student";
        //需要对象描述sql里的情况
        PreparedStatement statement = connection.prepareStatement(sql);
        //执行语句
        ResultSet resultset = statement.executeQuery();  //Resultset 结果集合
        while (resultset.next()){
            //使用get方法获取到每一列
            int id = resultset.getInt("id");
            String name = resultset.getString("name");
            System.out.println(id+":"+name);
        }

        //释放资源
        resultset.close();
        statement.close();
        connection.close();
    }
}
